#include "mkpiewidget.h"

#include "mkcore/mkcore.h"
#include "mkcore/mksettings.h"

#include <QPainter>
#include <QPaintEvent>

#include <QDebug>

MKPieTypeWidget::MKPieTypeWidget(QMap<quint8, quint32> costs, QWidget *parent)
	: QWidget(parent), mPieParts(costs), totalValue(0)
{
	setFixedSize(350, 230);

	foreach(double value, costs.values())
	{
		totalValue += value;
	}

}

void MKPieTypeWidget::paintEvent(QPaintEvent *event)
{
	if (totalValue == 0)
	{
		QWidget::paintEvent(event);
		return;
	}

	QPainter painter(this);

	QRectF pieRectangle(10, 10, 210, 210);
	int startAngle = 0;

	int i = 0;
	MKSettings *settings = MKCore::instance()->settings();
	foreach (quint8 key, mPieParts.keys())
	{
		quint32 spanAngle = static_cast<quint32>((static_cast<double>(mPieParts[key]) / static_cast<double>(totalValue)) * 360 * 16);
		painter.setRenderHint(QPainter::Antialiasing, true);
		painter.setBrush(QBrush(Qt::GlobalColor(Qt::green - i++), Qt::SolidPattern));
		painter.drawPie(pieRectangle, startAngle, spanAngle);
		startAngle += spanAngle;

		QRectF colorRectangle(240, 20 * i, 10, 10);
		painter.drawRect(colorRectangle);

		painter.drawText(QPointF(260, 9 + 20 * i), settings->typeRuName(key));
	}
	QWidget::paintEvent(event);
}

///---------------------------------------------------------------------------------------------------------------

MKPieCategoryWidget::MKPieCategoryWidget(QMap<quint8, QMap<quint8, quint32> > costs, QWidget *parent)
	: QWidget(parent), mPieParts(costs), totalValue(0)
{
	setFixedSize(350, 230);
	QMap<quint8, quint32> categoriesCosts;
	foreach(categoriesCosts, costs.values())
	{
		foreach (quint32 categoryCost, categoriesCosts.values())
		{
			totalValue += categoryCost;
		}
	}
}

void MKPieCategoryWidget::paintEvent(QPaintEvent *event)
{
	if (totalValue == 0)
	{
		QWidget::paintEvent(event);
		return;
	}

	QPainter painter(this);

	QRectF pieRectangle(10, 10, 210, 210);
	int startAngle = 0;

	int i = 0;
	MKSettings *settings = MKCore::instance()->settings();
	foreach (quint8 type, mPieParts.keys())
	{
		foreach (quint8 category, mPieParts[type].keys())
		{
			quint32 cost = mPieParts[type][category];

			quint32 spanAngle = static_cast<quint32>((static_cast<double>(cost) / static_cast<double>(totalValue)) * 360 * 16);
			painter.setRenderHint(QPainter::Antialiasing, true);
			painter.setBrush(QBrush(Qt::GlobalColor(Qt::red + i++), Qt::SolidPattern));
			painter.drawPie(pieRectangle, startAngle, spanAngle);
			startAngle += spanAngle;

			QRectF colorRectangle(240, 20 * i, 10, 10);
			painter.drawRect(colorRectangle);

			painter.drawText(QPointF(260, 9 + 20 * i), settings->categoryRuName(type, category));
		}
	}
	QWidget::paintEvent(event);
}
